package com.baizhi.service.impl;

import com.baizhi.entity.*;
import com.baizhi.mapper.*;
import com.baizhi.service.CmfzShiroService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
public class CmfzShiroServiceImpl implements CmfzShiroService {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private CmfzAdminRoleMapper cmfzAdminRoleMapper;
    @Autowired
    private CmfzRoleMapper cmfzRoleMapper;
    @Autowired
    private CmfzResourceMapper cmfzResourceMapper;
    @Autowired
    private CmfzRoleResourceMapper cmfzRoleResourceMapper;
    @Transactional
    public Set<String> selectRoleNameByUsername(String username) {
        Admin admin = adminMapper.selectOne(new QueryWrapper<Admin>().eq("username", username));
        List<CmfzAdminRole> adminRoles = cmfzAdminRoleMapper.selectList(new QueryWrapper<CmfzAdminRole>().eq("admin_id", admin.getId()));
        Set<String> roles = new HashSet<>();
        for(CmfzAdminRole adminRole:adminRoles){
            CmfzRole cmfzRole = cmfzRoleMapper.selectById(adminRole.getRoleId());
            if(cmfzRole!=null){
                roles.add(cmfzRole.getRoleName());
            }
        }
        return roles;
    }

    @Override
    public Set<String> selectPermissionByUsername(String username) {
        Set<String> roles = selectRoleNameByUsername(username);
        Set<String> permissions = new HashSet<>();
         for(String roleName:roles){
             List<CmfzRoleResource> roleResources = cmfzRoleResourceMapper.selectList(new QueryWrapper<CmfzRoleResource>().eq("role_name", roleName));
             for(CmfzRoleResource roleResource:roleResources){
                 CmfzResource cmfzResource = cmfzResourceMapper.selectOne(new QueryWrapper<CmfzResource>().eq("resource_id",roleResource.getResourceId()).eq("resource_type","function"));
                 if(cmfzResource!=null){
                     permissions.add(cmfzResource.getResourcePermission());
                 }
             }
         }
         return permissions;
    }
}
